<template>
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>
  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length===0">请选择标签</div>
  <van-row gutter="16">
    <van-col v-for="tag in activeIds">
      <van-tag closeable size="medium" type="primary" @close="close(tag)">
        {{ tag }}
      </van-tag>
    </van-col>
  </van-row>
  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <van-button class="searchbtn" type="primary" @click="doSearchResult">
    搜索
  </van-button>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue';
import {showToast} from 'vant';
import {useRouter} from "vue-router";
const route =useRouter();

const searchText = ref('');
const activeIds = ref<string[]>([]);
const activeIndex = ref(0);

// 原始数据保持不变
const originalTagList = [
  {
    text: '性别',
    children: [
      {text: '男', id: "男"},
      {text: '女', id: "女"}
    ],
  },
  {
    text: '年级',
    children: [
      {text: '大一', id: "大一"},
      {text: '大二', id: "大二"},
      {text: '大三', id: "大三"},
      {text: '大四', id: "大四"},
      {text: '研一', id: "研一"},
      {text: '研二', id: "研二"}
    ],
  }
];

// 使用计算属性动态过滤
const tagList = computed(() => {
  if (!searchText.value) {
    return originalTagList;
  }
  return originalTagList.map(parentTag => ({
    ...parentTag,
    children: parentTag.children.filter(item =>
        item.text.includes(searchText.value)
    )
  }));
});

/**
 * 搜索
 * @param val
 */
const onSearch = (val: string) => {
  // 只需要更新 searchText，tagList 会自动更新
  searchText.value = val;
  console.log(tagList.value);
};
/**
 * 取消
 */
const onCancel = () => showToast('取消');
/**
 * 关闭
 * @param tag
 */
const close = (tag:any) => {
  activeIds.value = activeIds.value.filter(item => item !== tag);
};
/**
 * 搜索结果
 * @param tag
 */
const doSearchResult = () => {
  route.push({
    path: '/searchResult',
    query: {
      tags: activeIds.value
    }
  });
};
</script>

<style scoped>
.searchbtn {
  display: block;
  margin: 0 auto;
}

</style>